package com.xh.rufongwallpaper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xh.rufongwallpaper.entity.Device;
import com.xh.rufongwallpaper.mapper.DeviceMapper;
import com.xh.rufongwallpaper.service.DeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;

/**
 * 设备服务实现类
 *
 * @author XH
 */
@Service
@RequiredArgsConstructor
public class DeviceServiceImpl implements DeviceService {

    private final DeviceMapper deviceMapper;

    @Override
    @Transactional
    public Device registerDevice(Device device) {
        // 如果设备已存在，则返回已有设备
        Device existingDevice = deviceMapper.selectOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getDeviceId, device.getDeviceId())
                        .eq(Device::getIsDeleted, false)
        );
        
        if (existingDevice != null) {
            // 更新最后活跃时间
            existingDevice.setLastActiveTime(new Date());
            deviceMapper.updateById(existingDevice);
            return existingDevice;
        }
        
        // 设置初始值
        if (device.getLastActiveTime() == null) {
            device.setLastActiveTime(new Date());
        }
        device.setIsDeleted(false);
        
        deviceMapper.insert(device);
        return device;
    }

    @Override
    @Transactional
    public boolean updateDeviceActiveTime(String deviceId) {
        Device device = deviceMapper.selectOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getDeviceId, deviceId)
                        .eq(Device::getIsDeleted, false)
        );
        
        if (device != null) {
            return deviceMapper.update(null,
                    new LambdaUpdateWrapper<Device>()
                            .eq(Device::getId, device.getId())
                            .eq(Device::getIsDeleted, false)
                            .set(Device::getLastActiveTime, LocalDateTime.now())
            ) > 0;
        }
        return false;
    }

    @Override
    public Optional<Device> getDeviceByDeviceId(String deviceId) {
        return Optional.ofNullable(deviceMapper.selectOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getDeviceId, deviceId)
                        .eq(Device::getIsDeleted, false)
        ));
    }

    @Override
    public boolean existsDeviceByDeviceId(String deviceId) {
        return deviceMapper.exists(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getDeviceId, deviceId)
                        .eq(Device::getIsDeleted, false)
        );
    }
} 